package at.fhhagenberg.hydrac.backend.codegenerators;

import at.fhhagenberg.hydrac.backend.javacc.nodes.ASTIdent;
import at.fhhagenberg.hydrac.backend.javacc.nodes.ASTType;
import at.fhhagenberg.hydrac.backend.javacc.nodes.Node;

import com.google.common.base.Predicate;

public class CGUtil {

  public static String getIdent(Node n) {
    if (n instanceof ASTIdent) {
      return ((ASTIdent) n).getValue();
    } else if (n != null) {
      for (int i = 0; i < n.jjtGetNumChildren(); i++) {
        String result = getIdent(n.jjtGetChild(i));
        if (result != null) {
          return result;
        }
      }
    }
    return null;
  }

  public static String getType(Node n) {
    if (n instanceof ASTType) {
      return ((ASTType) n).getValue();
    } else if (n != null) {
      for (int i = 0; i < n.jjtGetNumChildren(); i++) {
        String result = getType(n.jjtGetChild(i));
        if (result != null) {
          return result;
        }
      }
    }
    return null;
  }

  public static Node getSibling(Node n) {
    Node parent = n.jjtGetParent();

    Node sibling = null;
    for (int i = 0; i < parent.jjtGetNumChildren(); i++) {
      if (parent.jjtGetChild(i).equals(n)) {
        return sibling;
      }
      sibling = parent.jjtGetChild(i);
    }
    return sibling;
  }

  public static void forEachChild(Node n, Predicate<Node> f) {
    for (int i = 0; i < n.jjtGetNumChildren(); i++) {
      f.apply(n.jjtGetChild(i));
    }
  }

}
